package com.situ.day24.recursion;

import org.junit.Test;

public class RecursionDemo {
    private static int count = 0;

    public static void main(String[] args) {
        fun();
    }

    //java.lang.StackOverflowError
    private static void fun() {
        count++;
        System.out.println("count: " + count);
        fun();
        System.out.println("RecursionDemo.fun");
    }

    @Test
    public void test1() {
        int result = factorial(5);
        System.out.println(result);
    }

    // 5!=5*4*3*2*1
    // factorial(5)=5*factorial(4)=5*24
    // factorial(4)=4*factorial(3)=4*6=24
    // factorial(3)=3*factorial(2)=3*2=6
    // factorial(2)=2*factorial(1)=2*1=2
    // factorial(1)=1
    public int factorial(int n) {
        if (n == 1) {
            return 1;
        }
        return n * factorial(n - 1);
    }


    @Test
    public void test2() {
        int result = fibonacci(5);
        System.out.println(result);
    }

    public int fibonacci(int n) {
        if (n == 0 || n ==1) {
            return n;
        }
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}
